package com.familyaccount.servlet;

import com.familyaccount.service.UserService;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/forgotPassword")
public class ForgotPasswordServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String email = request.getParameter("email");

        try {
            boolean success = userService.createPasswordResetRequest(email);
            if (success) {
                request.setAttribute("success", "密码重置申请已提交，请等待管理员审核。");
            } else {
                request.setAttribute("error", "未找到该邮箱对应的用户。");
            }
        } catch (SQLException e) {
            request.setAttribute("error", "处理请求时发生错误，请稍后重试。");
        }

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.sendRedirect("index.jsp");
    }
} 